//
//  ZFCountdownView.m
//  ZFCountdownView
//
//  Created by fyzq on 2021/9/8.
//

#import "ZFCountdownView.h"
#define ZFWeakSelf __weak typeof(self) weakSelf = self
#define ZFStrongSelf __strong typeof(weakSelf) strongSelf = weakSelf;
@interface ZFCountdownView()
@property(nonatomic,copy)NSMutableArray *typeArr;


@end
@implementation ZFCountdownView
- (instancetype)init
{
    self = [super init];
    if (self) {
        _typeArr = [NSMutableArray array];
        _items = [NSMutableArray array];
    }
    return self;
}

-(MarkerBlock)addYear{
    return [self addCustom:ZFCountdownViewTimeTypeYear];
}
-(MarkerBlock)addMonth{
    return [self addCustom:ZFCountdownViewTimeTypeMonth];
}
-(MarkerBlock)addDay{
    return [self addCustom:ZFCountdownViewTimeTypeDay];
}
-(MarkerBlock)addHour{
    return [self addCustom:ZFCountdownViewTimeTypeHour];
}
-(MarkerBlock)addMinute{
    return [self addCustom:ZFCountdownViewTimeTypeMintue];
}
-(MarkerBlock)addSecond{
    return [self addCustom:ZFCountdownViewTimeTypeSecond];
}
-(MarkerBlock)addCustom:(ZFCountdownViewTimeType)type{
    ZFWeakSelf;
    return ^(NSString *title){
        ZFStrongSelf;
        [strongSelf.typeArr addObject:@{@"title":title,@"type":@(type)}];
        return self;
    };
}

-(ZFCountdownView *)layoutSubview:(ZFTipConfig *)config{
    [self.items removeAllObjects];
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSSortDescriptor *descripor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES];
    NSArray *arr= [self.typeArr sortedArrayUsingDescriptors:@[descripor]];
    NSString *layoutStr = @"H:|-0-";
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (int i=0;i<arr.count;i++) {
        NSDictionary *itemDic = arr[i];
        ZFCountdownItemView *itemView = [ZFCountdownItemView new];
        itemView.tip = itemDic[@"title"];
        itemView.config = config;
        itemView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:itemView];
        [self.items addObject:itemView];
        if (i == arr.count-1) {
            layoutStr = [layoutStr stringByAppendingFormat:@"[item%d]-0-|",i];
        }else{
            layoutStr = [layoutStr stringByAppendingFormat:@"[item%d]-%f-",i,config.tipspace];
        }
        [dic setValue:itemView forKey:[NSString stringWithFormat:@"item%d",i]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[itemView]-0-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(itemView)]];
    }
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:layoutStr options:0 metrics:0 views:dic]];
    self.typeArr = [arr mutableCopy];
    return self;;
}

////开始时间戳
-(ZFCountdownView *)startCountDownType:(ZFCountdownViewType)type time:(NSTimeInterval)time{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time];
    __block int x = [date timeIntervalSinceNow];
    ZFTimer *timer = [ZFTimer new];
    ///计算年月日计算比例
    NSArray *calculateArr = [self calculateScale];
    ZFWeakSelf;
    [timer startTimer:^{
        
        if (x<=0) {
            [timer close];
            return;
        }
        ZFStrongSelf;
        [strongSelf.items enumerateObjectsUsingBlock:^(ZFCountdownItemView*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary *scale = calculateArr[idx];
            int s = [scale[@"s"] intValue];
            int y = [scale[@"y"] intValue];
            int d = y ==0 ? x/s: x/s % y;
            obj.title = d<10? [NSString stringWithFormat:@"0%d",d]:[NSString stringWithFormat:@"%d",d];
        }];
        x--;
    }];

  
    
    return self;
}
-(NSMutableArray *)calculateScale{
    NSMutableArray *calculateArr = [NSMutableArray array];
    [self.typeArr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        switch ([obj[@"type"] intValue]) {
            case ZFCountdownViewTimeTypeYear:
                break;
            case ZFCountdownViewTimeTypeMonth:
                [calculateArr addObject:@{@"s":@(60*60*24*12),@"y":@0}];
                break;
            case ZFCountdownViewTimeTypeDay:
                [calculateArr addObject:@{@"s":@(60*60*24),@"y":@0}];
                break;
            case ZFCountdownViewTimeTypeHour:
                [calculateArr addObject:@{@"s":@(60*60),@"y":@24}];
                break;
            case ZFCountdownViewTimeTypeMintue:
                [calculateArr addObject:@{@"s":@60,@"y":@60}];
                break;
            case ZFCountdownViewTimeTypeSecond:
                [calculateArr addObject:@{@"s":@1,@"y":@60}];
                break;
            default:
                break;
        }
    }];
    return calculateArr;
}

@end
@interface ZFCountdownItemView()
@property(nonatomic,strong)UIButton *button;
@property(nonatomic,strong)UILabel *label;
@property(nonatomic,copy)NSArray<NSLayoutConstraint *> *constraints;
@end
@implementation ZFCountdownItemView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initZFCountdownItemView];
    }
    return self;
}

-(void)initZFCountdownItemView{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"10" forState:UIControlStateNormal];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:button];
    _button = button;
    
    UILabel *label = [UILabel new];
    label.text = @"";
    label.textAlignment = NSTextAlignmentCenter;
    label.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:label];
    _label = label;
    self.constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[button]-space-[label]-0-|" options:0 metrics:@{@"space":@2} views:NSDictionaryOfVariableBindings(button,label)];
    [self addConstraints:self.constraints];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[button]-0-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(button)]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    
    [self addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"tip" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"title"]) {
        [self.button setTitle:change[@"new"] forState:UIControlStateNormal];
    } else if ([keyPath isEqualToString:@"tip"]) {
        self.label.text = change[@"new"];
    }else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)setConfig:(ZFTipConfig *)config{
    _config = config;
    self.button.titleLabel.font = config.timeFont;
    [self.button setTitleColor:config.timeColor forState:UIControlStateNormal];
    [self.button setContentEdgeInsets:config.timeInsets];
    self.button.backgroundColor = config.timeBackgroundColor;
    self.button.layer.cornerRadius = config.timeRadius;
    self.button.layer.masksToBounds = YES;
    
    self.label.textColor = config.tipColor;
    self.label.font = config.tipFont;
    self.label.backgroundColor = config.tipBackgroundColor;

    [self removeConstraints:self.constraints];
    self.constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[button]-space-[label]-0-|" options:0 metrics:@{@"space":@(config.tipspace)} views:@{@"button":self.button,@"label":self.label}];
    [self addConstraints:self.constraints];
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"title"];
    [self removeObserver:self forKeyPath:@"tip"];
}
@end


@implementation ZFTipConfig

- (instancetype)init
{
    self = [super init];
    if (self) {
        _timeFont = [UIFont boldSystemFontOfSize:14];
        _timeColor = UIColor.whiteColor;
        _timeBackgroundColor = UIColor.orangeColor;
        _timeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
        _timeRadius = 3;
        _tipFont = [UIFont systemFontOfSize:14];
        _tipspace = 3;
        _tipColor = UIColor.grayColor;
        _tipBackgroundColor = UIColor.clearColor;
    }
    return self;
}

@end

@interface ZFTimer()
@property (nonatomic,strong) ZFTimerBlock block;
@property(nonatomic,copy)CADisplayLink *displayLink;
@end
@implementation ZFTimer

-(void)startTimer:(ZFTimerBlock)handler{
    if (self.displayLink) {
        [self close];
    }
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
    displayLink.preferredFramesPerSecond = 1;
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    self.block = handler;
    _displayLink = displayLink;
}
-(void)handleDisplayLink:(CADisplayLink *)link{
    self.block();
//    NSLog(@"dadda");
}
-(void)close{
    [self.displayLink invalidate];
}
-(void)dealloc{
    [self close];
}
@end
